package com.timothy.junk.gfund.activity;

import java.io.IOException;
import java.util.List;

import org.apache.commons.httpclient.HttpException;

import com.sina.oefund.SinaOEFund;
import com.sina.oefund.SinaOEFundClient;
import com.sina.stock.SinaStockClient;
import com.sina.stock.SinaStockInfo;
import com.sina.stock.SinaStockInfo.ParseStockInfoException;
import com.sina.util.StringUtil;
import com.timothy.junk.R;
import com.timothy.junk.ActivityManage;
import com.timothy.junk.calculate.GFundCalculator;
import com.timothy.junk.common.parse.ParseXML;
import com.timothy.junk.common.util.DateUtil;
import com.timothy.junk.common.util.NetWorkUtil;
import com.timothy.junk.gfund.bean.GFundBean;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class GFundDetail extends Activity {
	public static final String LOG_TAG = "GFundDetail";
	
	//fundA
	TextView fundAName;
	TextView fundAPrice;
	TextView fundAValue;
	TextView fundADiscount;
	
	//fundB
	TextView fundBName;
	TextView fundBPrice;
	TextView fundBValue;
	TextView fundBDiscount;
	
	//AB Merge
	TextView fundABRatio;
	TextView fundABMergePrice;
	
	//fundM
	TextView fundMName;
	TextView fundMValue;
	TextView fundMValueDate;
	TextView fundMValueEstimate;

	//fundM
	TextView fundMIndexName;
	TextView fundMIndexPrice;
	TextView fundMIndexRise;
	TextView fundMIndexDate;
	
	//Total
	TextView totalDisount;
	TextView arbSpace;
	TextView yearReturn;
	
	Context mContext;
	
	GFundBean bean;
	String[] abFundMIndex = new String[3];
	List<SinaStockInfo> abFundMIndexList;
	SinaStockInfo sFundA;
	SinaStockInfo sFundB;
	SinaStockInfo fundMIndex;
	
	List<SinaOEFund> fundList;
	SinaOEFund fundA;
	SinaOEFund fundB;
	SinaOEFund fundM;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gfund_list_detail);
        
        mContext = getApplicationContext();
        ActivityManage.add(this);
        
        Bundle bundle = this.getIntent().getExtras();
        String index = bundle.getString("index");
        bean = ParseXML.getGFundByIndex(mContext, index);
        
		fundAName = (TextView) findViewById(R.id.fundAName);
		fundAPrice = (TextView) findViewById(R.id.fundAPrice);
		fundAValue = (TextView) findViewById(R.id.fundAValue);
		fundADiscount = (TextView) findViewById(R.id.fundADiscount);
		
		fundBName = (TextView) findViewById(R.id.fundBName);
		fundBPrice = (TextView) findViewById(R.id.fundBPrice);
		fundBValue = (TextView) findViewById(R.id.fundBValue);
		fundBDiscount = (TextView) findViewById(R.id.fundBDiscount);
		
		fundABRatio = (TextView) findViewById(R.id.fundABRatio);
		fundABMergePrice = (TextView) findViewById(R.id.fundABMergePrice);
		
		fundMName = (TextView) findViewById(R.id.fundMName);
		fundMValue = (TextView) findViewById(R.id.fundMValue);
		fundMValueDate = (TextView) findViewById(R.id.fundMValueDate);
		fundMValueEstimate = (TextView) findViewById(R.id.fundMValueEstimate);

		fundMIndexName = (TextView) findViewById(R.id.fundMIndexName);
		fundMIndexPrice = (TextView) findViewById(R.id.fundMIndexPrice);
		fundMIndexRise = (TextView) findViewById(R.id.fundMIndexRise);
		fundMIndexDate = (TextView) findViewById(R.id.fundMIndexDate);
		
		totalDisount = (TextView) findViewById(R.id.totalDisount);
		arbSpace = (TextView) findViewById(R.id.arbSpace);
		yearReturn = (TextView) findViewById(R.id.yearReturn);
		
        if(NetWorkUtil.isNetworkAvailable(mContext)){
        	new GetDataTask().execute();
        }else{
        	Toast.makeText(mContext, "Your network is not available!", Toast.LENGTH_LONG).show();
        }
    }

    public void loadData(){
    	abFundMIndex[0] = bean.getFundACode();
    	abFundMIndex[1] = bean.getFundBCode();
    	abFundMIndex[2] = bean.getFundMIndexCode();
    	
    	try {
			abFundMIndexList = SinaStockClient.getInstance().getStockInfoList(abFundMIndex);
			if(abFundMIndexList!=null && abFundMIndexList.size() == 3){
				sFundA = abFundMIndexList.get(0);
				sFundB = abFundMIndexList.get(1);
				fundMIndex = abFundMIndexList.get(2);
			}
			
			String transFundACode = StringUtil.transferCode(bean.getFundACode());
			String transFundBCode = StringUtil.transferCode(bean.getFundBCode());
			fundList =  SinaOEFundClient.getInstance().getFundList(new String[]{transFundACode,transFundBCode,bean.getFundMCode()});
			if(fundList!=null && fundList.size() == 3){
				fundA = fundList.get(0);
				fundB = fundList.get(1);
				fundM = fundList.get(2);
			}
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseStockInfoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (com.sina.oefund.SinaOEFund.ParseStockInfoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
    	
    }
    
    public void displayData(){
		fundAName.setText(bean.getFundAName());
		fundAPrice.setText(String.valueOf(sFundA.getNowPrice()));
		fundAValue.setText(String.valueOf(fundA.getPrice()));
		fundADiscount.setText(StringUtil.formatData2Deci(StringUtil.getDiscount(fundA.getPrice(), sFundA.getNowPrice()))+"%");
		
		fundBName.setText(bean.getFundBName());
		fundBPrice.setText(String.valueOf(sFundB.getNowPrice()));
		fundBValue.setText(String.valueOf(fundB.getPrice()));
		fundBDiscount.setText(StringUtil.formatData2Deci(StringUtil.getDiscount(fundB.getPrice(), sFundB.getNowPrice()))+"%");
		
		//AB Merge
		fundABRatio.setText(String.valueOf(bean.getFundAShare())+":"+ String.valueOf(bean.getFundBShare()));
		double totalPrice = sFundA.getNowPrice() * bean.getFundAShare() + sFundB.getNowPrice() * bean.getFundBShare();
		double totalShare = bean.getFundAShare()+bean.getFundBShare();
		double mergerPrice = totalPrice/totalShare;
		Log.i(LOG_TAG,"totalPrice:"+String.valueOf(totalPrice));
		Log.i(LOG_TAG,"totalShare:"+String.valueOf(totalShare));
		Log.i(LOG_TAG,"mergerPrice:"+String.valueOf(mergerPrice));
		
		fundABMergePrice.setText(StringUtil.formatData4Deci(mergerPrice));
		
		
        float rise = (fundMIndex.getNowPrice() - fundMIndex.getYestodayPrice()) / fundMIndex.getYestodayPrice();
		fundMIndexName.setText(fundMIndex.getName());
		fundMIndexPrice.setText(String.valueOf(fundMIndex.getNowPrice()));
		fundMIndexDate.setText(fundMIndex.getDate());
		fundMIndexRise.setText(StringUtil.formatData2Deci(rise*100)+"%");
		
		fundMName.setText(bean.getFundMName());
		fundMValue.setText(StringUtil.formatData4Deci(fundM.getPrice()));
		fundMValueDate.setText(fundM.getPriceDate());
		
		double valueEst =  0;
		if(DateUtil.compareDate(fundMIndex.getDate(), fundM.getPriceDate()) == 1){
			double riseEst = rise * bean.getFundMIndexRatio();
			Log.i(LOG_TAG,"value rise:"+String.valueOf(riseEst));
			
			valueEst =  (1.0 + riseEst) * fundM.getPrice();
			Log.i(LOG_TAG,"valueEst:"+String.valueOf(valueEst));
		}else{
			valueEst =  fundM.getPrice();
			Log.i(LOG_TAG,"last day value:"+String.valueOf(valueEst));
		}
		fundMValueEstimate.setText(StringUtil.formatData4Deci(valueEst));
		double tDiscount = (valueEst - mergerPrice)/valueEst;
		totalDisount.setText(StringUtil.formatData2Deci(tDiscount*100) + "%");
		
		double arbValue = 0.0;
		double yReturnValue = 0.0;
		if(tDiscount>0){
			arbValue = GFundCalculator.arbSpaceDis(Math.abs(tDiscount));
		}else{
			arbValue = GFundCalculator.arbSpacePre(Math.abs(tDiscount));
		}
		arbValue = arbValue>0?arbValue:0.0;
		arbSpace.setText(StringUtil.formatData2Deci(arbValue*100) + "%");
		
		if(tDiscount>0){
			yReturnValue = GFundCalculator.getDisYearReturn(arbValue);
		}else{
			yReturnValue = GFundCalculator.getPreYearReturn(arbValue);
		}
		yearReturn.setText(StringUtil.formatData2Deci(yReturnValue*100) + "%");
		
    }
    
    private class GetDataTask extends AsyncTask<Void, Void, String[]> {
        @Override
        protected String[] doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(2000);
                loadData();
            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String[] result) {
            super.onPostExecute(result);
			if (bean != null && sFundA != null && sFundB != null && fundMIndex != null 
					&& fundA != null && fundB != null && fundM != null) {
				displayData();
			}
        }
    }
}
